APIKEY="fVkmSOXCgorPfvJ8Kl0ZKnIq"
secret_key="pOReWqziKfQXXMJ4WJDwbvwjnKtm6LKj"

import ischinese
import requests
import json,time,os
import pandas as pd

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKEY+"&client_secret="+secret_key
    print(url)   
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main(i,theme,name,token):
    print(i)
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + token
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                #"content": "If you are a chef from a five-star hotel who excels in making creative dishes. Please make a %s themed %s suitable for American taste for your guests. Require that raw materials are easily available in supermarkets in the United States. Please list the ingredients, preparation methods, and dish characteristics."%(theme,name)
                "content": "If you are a chef at a five-star hotel, skilled in making creative dishes. Please make a dish of %s for 8 people that is suitable for American taste and themed around% s for your guests. Require that raw materials are easily available in supermarkets in the United States. Please list the ingredients and weight, preparation time, cooking time, cooking difficulty (1-5 levels, from simple to difficult), preparation method steps, nutritional ingredient list (including calories), dish characteristics, and 3-5 user comments. If there are any special precautions, please also list tips. The reply text must be output in full English (excluding Chinese characters)."%(name,theme)
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, timeout=120, headers=headers, data=payload)
    except requests.exceptions.RequestException:
        return False
    if ischinese.judge(response.text): return False
    result = json.loads(response.text)
    if 'result' not in result: return False
    else:
        with open("./recipes/%d.md"%i,"w") as f:
            f.write(result['result']+"\n")
    print(response.text)
    return True
    

if __name__ == '__main__':
    candidate = set([ item.split("\t")[0] for item in open("recipes.csv","r") ])
    count_id = set([ item.split("/")[-1].split(".md")[0] for item in os.popen("ls ./recipes/*.md").read().split("\n") ])
    count_url = set([])
    file = pd.read_excel("allrecipes.xlsx")
    token = get_access_token()
    for i in range(66705,40551,-1): count_url.add(file.iloc[i]['URL'])
    for i in range(40551,0,-1):
        url = file.iloc[i]['URL']
        name = file.iloc[i]['菜名']
        theme = file.iloc[i]['分类']
        if url in candidate and url not in count_url and str(i) not in count_id: 
            count_url.add(url)
            ret = main(i,theme,name,token)
            repeat = 0
            while ret == False and repeat < 10:
                repeat += 1
                time.sleep(3) 
                ret = main(i,theme,name,token)
            time.sleep(3) 
